package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

@RestController
@RequestMapping("admin/product/test")
public class TestController {
    @Autowired
    private TestService testService;

    @GetMapping("testLock")
    public Result testLock(){
        testService.testLock();
        return Result.ok();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("Come on ! Baby!");
        });
        //runAsync 没有返回值 返回 为 null
        System.out.println(voidCompletableFuture.get());
    */
        /*CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("有返回值");
            return 1024;
        }).thenApply((t) -> {
            int i = 1/0;
            return 2*t;
        }).whenComplete((i,throwable) -> {
            System.out.println("i = " + i);
            System.out.println("throwable = " + throwable);
        }).exceptionally((t) -> {
            System.out.println("t throwable= " + t);
            return 404;
        });
        System.out.println("completableFuture = " + completableFuture.get());*/

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 50, 3L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        CompletableFuture<String> A = CompletableFuture.supplyAsync(() -> {
            return "hello";
        }, threadPoolExecutor);

        CompletableFuture<Void> B = A.thenAcceptAsync(s -> {
            delaySec(1);
            printCurrTime(s + " B ");
        }, threadPoolExecutor);

        CompletableFuture<Void> C = A.thenAcceptAsync(s -> {
            delaySec(3);
            printCurrTime(s + "C");
        }, threadPoolExecutor);

        B.get();
        C.get();

    }

    private static void printCurrTime(String s) {
        System.out.println("s = " + s);
    }

    private static void delaySec(int i) {
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
